package org.ruanjj.multithread.JUC;

import java.util.concurrent.atomic.AtomicReference;

//模仿ABA问题
public class AtomicReferenceDemo {
    public static void main(String[] args) throws InterruptedException {
        AtomicReference<Integer> integerAtomicReference = new AtomicReference<>(100);
        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"获取到的值是"+integerAtomicReference.get());

            //先把100改成101
            boolean result1 = integerAtomicReference.compareAndSet(100, 101);
            System.out.println(Thread.currentThread().getName()+"修改成功否"+result1);

            //后又把101改回去了
            boolean result2 = integerAtomicReference.compareAndSet(101,100);
            System.out.println(Thread.currentThread().getName()+"修改成功否"+result2);

        },"t1").start();

        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"获取到的值是"+integerAtomicReference.get());
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //先把100改成101，模拟在B线程无感知的情况下，A线程已经把原值从100改到了101又改到了100
            boolean result1 = integerAtomicReference.compareAndSet(100, 101);
            System.out.println(Thread.currentThread().getName()+"修改成功否"+result1);

        },"t2").start();

        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName()+"修改之后的值是"+integerAtomicReference.get());
    }
}
